// 默认显示图片
// import _default from '@/assets/images/loading1.gif';
const _loading = new URL(`../assets/images/lazyloading.svg`, import.meta.url).href;
const _default = new URL(`../assets/images/default.svg`, import.meta.url).href;

/**
 * 懒加载指令v-zlazy="xxxx"
 * @param {Vue} app - vue实例
 * @param {HTMLElement} el - 图片DOM
 * @param {any} bindings - 绑定事件, 表示指令相关的信息是一个对象，比如v-zlazy='xxxx'， bindings既是xxxx
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const defineDirective = (app: any) => {
  app.directive('zlazy', {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    mounted(el: any, bindings: any) {
      el.tagName === 'IMG' ? (el.src = _loading, el.classList.add('z-lazy')) : null;
      el.src = _loading;
      const oberver = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) {
          if (el.tagName === 'IMG') {
            // eslint-disable-next-line no-param-reassign
            el.src = bindings.value;
            el.classList.remove('z-lazy')
            // eslint-disable-next-line no-param-reassign
            el.onerror = () => {
              // eslint-disable-next-line no-param-reassign
              el.src = _default;
              el.style.background = 'var(--z-bg-menu)';
            };
          }
          oberver.unobserve(el); // 取消监听
        }
      });
      oberver.observe(el);
    },
  });
};

export default {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  install(app: any) {
    defineDirective(app);
  },
};
